//
//  ImageShowViewController.m
//  GentlemanAnime
//
//  Created by dlios on 15-7-2.
//  Copyright (c) 2015年 lanou3g.com 蓝欧科技. All rights reserved.
//

#import "ImageShowViewController.h"
#import "UIImageView+WebCache.h"
#import "ImageShowCollectionViewCell.h"
#import "MBProgressHUD.h"
#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height

typedef NS_ENUM(NSInteger, UpViewIsShow) {
    SHOU = 1,
    NOSHOU,
    CHANGING
};


@interface ImageShowViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UIScrollViewDelegate>

@property(nonatomic, assign)NSInteger oldShow;
@property(nonatomic, retain)UIView *upView;
@property(nonatomic, assign)UpViewIsShow isShow;
@property(nonatomic, retain)NSTimer *timer;
@property(nonatomic, retain)UIImageView *backGroundView;
@property(nonatomic, retain)UICollectionView *collectionView;
@property(nonatomic, retain)UILabel *titleLabel;
@property(nonatomic, retain)UIImage *tempImage;

@end

@implementation ImageShowViewController
- (void)dealloc {
    [[SDImageCache sharedImageCache] clearMemory];
    [_backGroundImage release];
    [_tempImage release];
    [_titleLabel release];
    [_pirArr release];
    [_collectionView release];
    [_backGroundView release];
    [_timer release];
    [_upView release];
    Block_release(_regainItemBlock);
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.isShow = SHOU;
    }
    return self;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.backGroundView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    self.backGroundView.backgroundColor = [UIColor clearColor];
    self.backGroundView.image = self.backGroundImage;
    [self.view addSubview:self.backGroundView];
    [_backGroundView release];
    
    // 创建一个毛玻璃效果
    UIBlurEffect *blur = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    // 创建一个用来显示模糊效果的view
    UIVisualEffectView *view = [[UIVisualEffectView alloc] initWithEffect:blur];
    view.frame = self.view.bounds;
    [self.view addSubview:view];
    [view release];
    
    // 绘制collectionView
    [self createCollectionView];
    
    // 绘制上栏
    [self createUpView];
}

#pragma mark 绘制collectionView
- (void)createCollectionView {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(WIDTH - 20, HEIGHT - 80);
    // 设置滑动的方向(默认是垂直滑动)
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    // 设置最小列间距
    flowLayout.minimumInteritemSpacing = 20;
    flowLayout.minimumLineSpacing = 20;
    flowLayout.sectionInset = UIEdgeInsetsMake(40, 10, 40, 10);
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH,HEIGHT) collectionViewLayout:flowLayout];
    [self.view addSubview:self.collectionView];
    self.collectionView.backgroundColor = [UIColor clearColor];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.pagingEnabled = YES;
    self.collectionView.tag = 1000;
    self.collectionView.showsHorizontalScrollIndicator = YES;
    self.collectionView.contentOffset = CGPointMake(self.index * WIDTH, 0);
    [flowLayout release];
    [_collectionView release];
    
    // 创建手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    // 把手势添加到指定的控件上
    [self.collectionView addGestureRecognizer:tap];
    
    // 注册
    [self.collectionView registerClass:[ImageShowCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
}

#pragma mark 返回item个数方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.pirArr.count;
}

#pragma mark 生成item方法
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ImageShowCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];

    NSString *str = [NSString stringWithFormat:@"%@?imageView2/1/w/%1.0f/h/%1.0f",self.pirArr[indexPath.row],cell.frame.size.width,cell.frame.size.height];
    [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:str] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        [UIView animateWithDuration:2 animations:^{
            cell.picImageView.alpha = 1;
        } completion:^(BOOL finished) {
            cell.userInteractionEnabled = YES;
        }];
    }];
    
    return cell;
}

#pragma mark 绘制上栏
- (void)createUpView {
    self.upView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 64)];
    self.upView.backgroundColor = [UIColor colorWithWhite:0.000 alpha:0.700];
    self.upView.clipsToBounds = YES;
    [self.view addSubview:self.upView];
    [_upView release];
    // 返回按钮
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    backButton.frame = CGRectMake(0, 20, 44, 44);
    [backButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [backButton setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backButton setImageEdgeInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
    backButton.tintColor = [UIColor whiteColor];
    [backButton addTarget:self action:@selector(backButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.upView addSubview:backButton];
   
    
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, WIDTH / 3, 24)];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.center = CGPointMake(WIDTH / 2, 42);
    [self.upView addSubview:self.titleLabel];
    self.titleLabel.text = [NSString stringWithFormat:@"%d/%d",self.index + 1,self.pirArr.count];
    [_titleLabel release];
    
    // 自动隐藏上栏
    self.timer = [NSTimer scheduledTimerWithTimeInterval:4 target:self selector:@selector(hiddenUpView) userInfo:nil repeats:NO];
}


// 返回按钮方法
- (void)backButtonClick:(UIButton *)button {
    [self.timer invalidate];
    self.regainItemBlock();
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.collectionViewOffX = self.collectionView.contentOffset.x;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.tag == 1000) {
        // 算出偏移的值
        CGFloat offx = fabs (scrollView.contentOffset.x - self.collectionViewOffX);
        self.backGroundView.alpha = 1 - offx / WIDTH * 1.0;
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView.tag == 1000) {
        if (scrollView.contentOffset.x != self.collectionViewOffX) {
            NSInteger index = scrollView.contentOffset.x / WIDTH;
            self.backGroundView.alpha = 0;
            NSString *str = [NSString stringWithFormat:@"%@?imageView2/1/w/%1.0f/h/%1.0f",self.pirArr[index],WIDTH,HEIGHT];
            [self.backGroundView sd_setImageWithURL:[NSURL URLWithString:str] placeholderImage:[UIImage imageNamed:@"toumingzhanweitu"] animationBlock:^{
                [UIView animateWithDuration:0.7 animations:^{
                    self.backGroundView.alpha = 1;
                }];
            }];
            self.titleLabel.text = [NSString stringWithFormat:@"%d/%ld",index + 1,(unsigned long)self.pirArr.count];
        }
    }
    
}

#pragma mark 用定时器隐藏上栏的三个方法
// 自动隐藏上栏方法
- (void)hiddenUpView {
    if (self.isShow == SHOU) {
        self.oldShow = self.isShow;
        self.isShow = CHANGING;
        [UIView animateWithDuration:0.5 animations:^{
            self.upView.frame = CGRectMake(0, 0, WIDTH, 0);
        }];
        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];
        [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(changeIsShow) userInfo:nil repeats:NO];
    } else {
        
    }
}
// 0.45秒后更改上栏显示状态
- (void)changeIsShow {
    if (self.oldShow == SHOU) {
        self.isShow = NOSHOU;
    } else {
        self.isShow = SHOU;
    }
}

// 点击方法显示/隐藏上栏
- (void)tapAction:(UITapGestureRecognizer *)tap {
    // 判断是否
    if (self.isShow == SHOU) {
        self.oldShow = self.isShow;
        self.isShow = CHANGING;
        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];
        [UIView animateWithDuration:0.5 animations:^{
            self.upView.frame = CGRectMake(0, 0, WIDTH, 0);
            self.upView.alpha = 0;
        }];
        [NSTimer scheduledTimerWithTimeInterval:0.45 target:self selector:@selector(changeIsShow) userInfo:nil repeats:NO];
    } else if (self.isShow == NOSHOU) {
        self.oldShow = self.isShow;
        self.isShow = CHANGING;
        [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
        [UIView animateWithDuration:0.5 animations:^{
            self.upView.frame = CGRectMake(0, 0, WIDTH, 64);
            self.upView.alpha = 1;
        }];
        [NSTimer scheduledTimerWithTimeInterval:0.45 target:self selector:@selector(changeIsShow) userInfo:nil repeats:NO];
        [self.timer invalidate];
        self.timer = [NSTimer scheduledTimerWithTimeInterval:4 target:self selector:@selector(hiddenUpView) userInfo:nil repeats:NO];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
